<template>
  <div class="agora-video-view" :class="video === false ? 'show-placeholder' : ''">
    <div v-if="close" class="el-icon-close" @click="onClose"></div>
    <div :class="role === 'teacher' ? 'teacher-placeholder' : 'student-placeholder'"></div>
    <div class="video-profile" v-if="account">
      <span class="account">{{ account }}</span>
      <span class="media-btn" v-if="me.uid == id || me.role == 1">
        <div
          @click="handleClick('audio')"
          class="icon"
          :class="current_audio ? 'audio-on' : 'audio-off'"
        ></div>
        <div
          @click="handleClick('video')"
          class="icon"
          :class="current_video ? 'video-on' : 'video-off'"
        ></div>
      </span>
    </div>
    <div :id="domId" class="agora-rtc-video" :class="local ? 'rotateY180deg' : ''"></div>
  </div>
</template>

<script>
import { roomStore } from '../utils/room'
import { globalStore } from '../utils/global'
import { eduApi } from '../utils/edu-api'
import { t } from '../i18n/i18n'
export default {
  props: {
    domId: {
      type: [String, Number],
      default: ''
    },
    id: {
      type: [String, Number],
      default: ''
    },
    stream: {
      type: Object
    },
    streamID: {
      type: [String, Number],
      default: ''
    },
    account: {
      type: String,
      default: ''
    },
    role: {
      type: String,
      default: ''
    },
    audio: {
      type: Boolean,
      default: false
    },
    video: {
      type: Boolean,
      default: false
    },
    local: {
      type: Boolean,
      default: false
    },
    close: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      roomStore: roomStore,
      lockPlay: false,
      preview: true,
      current_domId: this.domId,
      current_id: this.id,
      current_stream: this.stream,
      current_streamID: this.streamID,
      current_account: this.account,
      current_role: this.role,
      current_audio: this.audio,
      current_video: this.video,
      current_local: this.local
    }
  },
  watch: {
    domId(val) {
      this.current_domId = val
    },
    id(n, o) {
      this.current_id = n
      if (n != o) {
        this.palyStream()
      }
    },
    stream: {
      deep: true,
      handler(newV, oldV) {
        this.current_stream = newV
        if (newV != oldV) {
          this.palyStream()
        }
      }
    },
    streamID(val) {
      this.current_streamID = val
    },
    account(val) {
      this.current_account = val
    },
    role(val) {
      this.current_role = val
    },
    audio(val) {
      this.current_audio = val
      this.$nextTick(() => {
        if (val) {
          this.current_stream.unmuteAudio()
        } else {
          this.current_stream.muteAudio()
        }
      })
    },
    video(val) {
      this.current_video = val
    },
    local(val) {
      this.current_local = val
    }
  },
  computed: {
    me() {
      return this.roomStore.state.me
    },
    usersList() {
      return this.roomStore.state.users
    }
  },
  mounted() {
    this.palyStream()
  },
  methods: {
    palyStream() {
      setTimeout(() => {
        if (
          !this.current_stream ||
          !this.current_domId ||
          (this.lockPlay && this.current_stream.isPlaying())
        )
          return
        this.lockPlay = true
        this.$nextTick(() => {
          this.current_stream.play(this.current_domId, { fit: 'cover' }, err => {
            this.lockPlay = false
            if (this.current_audio) {
              this.current_stream.unmuteAudio()
            } else {
              this.current_stream.muteAudio()
            }
          })
        })
        return () => {
          if (this.current_stream.isPlaying()) {
            this.current_stream.stop()
          }
        }
      }, 4000)
    },
    async handleClick(type) {
      const me = this.roomStore.state.me
      if (!this.roomStore.state.rtm.joined || !me.uid)
        return console.warn('please confirm joined rtm')
      let targetUser = ''
      for (const key in this.usersList) {
        if (this.usersList[key].uid === this.id) {
          targetUser = this.usersList[key]
        }
      }
      if (!targetUser) return
      // const teacherUid = this.roomStore.state.course.teacherId
      const targetUid = targetUser.uid
      const video = Boolean(targetUser.video)
      const audio = Boolean(targetUser.audio)
      const chat = Boolean(targetUser.chat)
      /* const uid = this.streamID || teacherUid
      const isLocal = uid === +me.uid */
      if (type === 'video') {
        if (video) {
          await this.roomStore.mute(targetUid, 'video')
        } else {
          await this.roomStore.unmute(targetUid, 'video')
        }
        return
      }
      if (type === 'audio') {
        if (audio) {
          // this.roomStore.rtcClient._localStream.muteAudio(uid, isLocal)
          await this.roomStore.mute(targetUid, 'audio')
        } else {
          // this.roomStore.rtcClient._localStream.unmuteAudio(uid, isLocal)
          await this.roomStore.unmute(targetUid, 'audio')
        }
        return
      }

      if (type === 'chat') {
        if (chat) {
          await this.roomStore.mute(targetUid, 'chat')
        } else {
          await this.roomStore.unmute(targetUid, 'chat')
        }
        return
      }
    },
    // 关闭连麦
    onClose() {
      const rtmClient = this.roomStore.rtmClient
      const rtcClient = this.roomStore.rtcClient
      const teacherUid = this.roomStore.state.course.teacherId
      const me = this.roomStore.state.me
      console.log(
        'close rtmClient: ',
        rtmClient,
        ', rtcClient: ',
        rtcClient,
        ', teacherUid: ',
        teacherUid
      )
      if (this.streamID === +me.uid && teacherUid) {
        this.roomStore.rtcClient._localStream.muteAudio(this.streamID, true)
        eduApi.studentStopCoVideo(this.roomStore.state.course.roomId)
        globalStore.showToast({
          type: 'close_youself_co_video',
          message: t('toast.close_youself_co_video')
        })
        globalStore.showVideo(true)
      }
      if (`${teacherUid}` && `${teacherUid}` === `${me.uid}`) {
        eduApi.teacherCancelStudent(
          this.roomStore.state.course.roomId,
          this.roomStore.state.applyUser.userId
        )
        this.roomStore.rtcClient._localStream.muteAudio(this.streamID, false)
        globalStore.showToast({
          type: 'peer_hands_up',
          message: t('toast.close_co_video')
        })
        roomStore.updateApplyUser({
          account: '',
          userId: ''
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.agora-video-view.show-placeholder {
  .video-profile {
    z-index: 9;
  }
  .teacher-placeholder,
  .student-placeholder {
    z-index: 9;
  }
  .agora-rtc-video {
    visibility: hidden;
  }
}

.video-profile {
  z-index: 3;
  width: 100%;
  height: 24px;
  position: absolute;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: space-between;
  align-items: center;
  .account {
    margin-left: 10px;
    line-height: 14px;
    font-size: 12px;
    color: #fff;
  }
}

.agora-video-view {
  margin: 0px 3.33px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  width: 237px;
  height: 132px;
  position: relative;
  overflow: hidden;
  .rotateY180deg {
    transform: rotateY(180deg);
  }

  .el-icon-close {
    position: absolute;
    top: 6px;
    right: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10;
    width: 18px;
    height: 18px;
    background-color: rgba(0, 0, 0, 0.4);
    border-radius: 8px;
    cursor: pointer;
    color: #999;
    font-size: 12px;
  }

  .media-btn {
    display: flex;
    justify-content: space-between;
    margin-right: 10px;

    .icon {
      width: 20px;
      height: 20px;
      background-repeat: no-repeat;
      background-position: center center;
      &.audio-on {
        background-image: url(~@assets/images/live/player_audio_on.png);
      }
      &.audio-off {
        background-image: url(~@assets/images/live/player_audio_off.png);
      }
      &.video-on {
        background-image: url(~@assets/images/live/player_video_on.png);
      }
      &.video-off {
        background-image: url(~@assets/images/live/player_video_off.png);
      }
    }
  }

  .agora-rtc-video {
    position: absolute;
    z-index: 2;
    height: 100%;
    width: 100%;
  }

  .teacher-placeholder,
  .student-placeholder {
    top: 0;
    left: 0;
    width: 100%;
    height: calc(100% - 24px);
    position: absolute;
    z-index: 2;
    display: flex;
    align-items: center;
    justify-content: center;
    font-family: 'eduline' !important;
    font-style: normal;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    background-color: #666666;
  }
  .student-placeholder::before,
  .teacher-placeholder::before {
    content: '';
    width: 46px;
    height: 47px;
    background-image: url(~@assets/images/live/player_close.png);
  }
}

.preview-video {
  .agora-rtc-video {
    display: flex;
    flex: 1;
    height: 100%;
    width: 100%;
    left: 0;
    position: absolute;
    overflow: hidden;
  }
}
</style>
